﻿using MainUI.Properties;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace MainUI
{
    public partial class HotkeySettingsWindow : Window
    {
        // 修复1：明确定义预设尺寸类型
        private class PresetSize
        {
            public string Display { get; set; }
            public string Value { get; set; }
        }

        private static readonly PresetSize[] _presetSizes =
        {
            new PresetSize { Display = "自定义", Value = "custom" },
            new PresetSize { Display = "800x600", Value = "800,600" },
            new PresetSize { Display = "1024x768", Value = "1024,768" },
            new PresetSize { Display = "1920x1080", Value = "1920,1080" }
        };

        public HotkeySettingsWindow()
        {
            InitializeComponent();
            InitializePresetSizes();
            LoadSettings();
            SetupEventHandlers();
        }

        // 修复2：使用强类型设置加载
        private void InitializePresetSizes()
        {
            AreaSize.ItemsSource = _presetSizes;
            AreaSize.DisplayMemberPath = "Display";
            AreaSize.SelectedValuePath = "Value";

            // 修复3：处理空值情况
            if (string.IsNullOrEmpty(Settings.Default.AreaSize))
            {
                Settings.Default.AreaSize = "custom";
            }
        }

        private void LoadSettings()
        {
            // 修复4：使用安全的类型转换
            AreaSize.SelectedValue = _presetSizes
                .FirstOrDefault(p => p.Value == Settings.Default.AreaSize)?.Value
                ?? "custom";

            FixedKeyBox.Text = Settings.Default.FixedHotkey;
            CustomKeyBox.Text = Settings.Default.CustomHotkey;
        }

        // 修复5：添加空值检查
        private void SetupEventHandlers()
        {
            if (FixedKeyBox != null)
                FixedKeyBox.PreviewKeyDown += (s, e) => CaptureHotkey(FixedKeyBox, e);

            if (CustomKeyBox != null)
                CustomKeyBox.PreviewKeyDown += (s, e) => CaptureHotkey(CustomKeyBox, e);

            if (SaveButton1 != null)
                SaveButton1.Click += (s, e) => SaveSettings();
        }

        // 修复6：增强键值过滤逻辑
        private void CaptureHotkey(TextBox textBox, KeyEventArgs e)
        {
            e.Handled = true;

            var modifiers = Keyboard.Modifiers;
            var key = e.Key == Key.System ? e.SystemKey : e.Key;

            // 修复7：使用枚举值判断替代字符串操作
            if (key.IsModifierKey()) return;

            textBox.Text = FormatHotkey(modifiers, key);
            textBox.Tag = new HotkeyData(modifiers, key);
        }

        private string FormatHotkey(ModifierKeys modifiers, Key key)
        {
            // 修复8：支持组合修饰键（例如Ctrl+Alt+S）
            var modifiersList = new System.Collections.Generic.List<string>();

            if (modifiers.HasFlag(ModifierKeys.Control))
                modifiersList.Add("Ctrl");
            if (modifiers.HasFlag(ModifierKeys.Alt))
                modifiersList.Add("Alt");
            if (modifiers.HasFlag(ModifierKeys.Shift))
                modifiersList.Add("Shift");
            if (modifiers.HasFlag(ModifierKeys.Windows))
                modifiersList.Add("Win");

            return modifiersList.Count > 0
                ? $"{string.Join("+", modifiersList)}+{key}"
                : key.ToString();
        }

        // 修复9：添加完整的异常处理
        private void SaveSettings()
        {
            try
            {
                if (AreaSize.SelectedValue == null)
                    throw new InvalidOperationException("请选择截图区域尺寸");

                Settings.Default.AreaSize = AreaSize.SelectedValue.ToString();
                SaveHotkeySetting(FixedKeyBox, nameof(Settings.Default.FixedHotkey));
                SaveHotkeySetting(CustomKeyBox, nameof(Settings.Default.CustomHotkey));

                Settings.Default.Save();
                DialogResult = true;
                Close();
            }
            catch (Exception ex) when (
                ex is InvalidOperationException ||
                ex is ArgumentException
            )
            {
                MessageBox.Show(ex.Message, "配置错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        // 修复10：重构设置保存逻辑
        private void SaveHotkeySetting(TextBox textBox, string propertyName)
        {
            if (textBox?.Tag is HotkeyData data)
            {
                ValidateHotkey(data);
                var propInfo = typeof(Settings).GetProperty(propertyName);
                propInfo?.SetValue(Settings.Default, textBox.Text);
            }
        }

        private void ValidateHotkey(HotkeyData data)
        {
            if (data.Key == Key.None)
                throw new ArgumentException("检测到无效的快捷键");

            // 修复11：禁止单独使用非功能键
            if (data.Modifiers == ModifierKeys.None &&
                !IsFunctionKey(data.Key))
            {
                throw new ArgumentException("必须包含修饰键（Ctrl/Alt/Shift）");
            }
        }

        private bool IsFunctionKey(Key key) =>
            key >= Key.F1 && key <= Key.F24;
    }

    // 修复12：公开HotkeyData类
    public class HotkeyData
    {
        public ModifierKeys Modifiers { get; }
        public Key Key { get; }

        public HotkeyData(ModifierKeys modifiers, Key key)
        {
            // 修复13：验证键值有效性
            if (key == Key.None)
                throw new ArgumentException("无效的按键值");

            Modifiers = modifiers;
            Key = key;
        }
    }

    // 修复14：添加扩展方法
    internal static class KeyExtensions
    {
        public static bool IsModifierKey(this Key key)
        {
            switch (key)
            {
                case Key.LeftCtrl:
                case Key.RightCtrl:
                case Key.LeftAlt:
                case Key.RightAlt:
                case Key.LeftShift:
                case Key.RightShift:
                    return true;
                default:
                    return false;
            }
        }
    }
}